import axios from 'axios';
import { MessageBox, Message } from 'element-ui'

const instance = axios.create({
  baseURL: process.env.VUE_APP_HTTP,
  timeout: 10000
});


instance.interceptors.request.use(config => {
  // 设置header头 通过接口权限验证
  if (!config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/json';
  }
  config.headers['Authorization'] = "Bearer " + sessionStorage.getItem('token') || ''
  return config;
});

instance.interceptors.response.use(response => {
  if(response.request.responseType === "arraybuffer" || response.request.responseType === "blob"){
    return Promise.resolve(response.data);
  }
  
  if (response.data.code === 200 && response.data.status == "success") {
    return Promise.resolve(response.data);
  } else {
    if (response.data.message === 'This action is unauthorized.') {
      Message.error('身份过期，请重新登录！');
      setTimeout(() => {
        sessionStorage.clear()
        window.location.href = '/login'
      }, 1200)
      return
    }
    if (response.data && response.data.message) Message.error({ message: response.data.message, showClose: true, });
    return Promise.reject(response.data);   //直接用catch捕获
  }
}, error => {
  console.log('error~~~~', error)
  if (error.message.includes('timeout')) {
    // Message.error('请求超时，请刷新重试');
  } else if (error.message.includes('404')) {
    Message.error('404');
  }
  return Promise.reject('error')
});



const get = (url, params = {}, config = {}) => {
  return instance({ method: 'GET', url, params, ...config })
};
const post = (url, data = {}, config = {}) => {
  return instance({ method: 'POST', url, data, ...config })
};
const put = (url, data, config = {}) => {
  return instance({ method: "PUT", url, data, ...config })
};
const del = (url, data, config = {}) => {
  return instance({ method: "DELETE", url, data, ...config })
};




export { get, post, put, del}


